package org.scboy.dbms.detect;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseServersDao;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 服务器心跳检测
 */
@Configuration
@EnableScheduling
public class ServerDetect  implements ApplicationListener<ApplicationReadyEvent>{
	
	Log log=LogFactory.get();
	
	@Autowired
	EntityFactory factory;
	
	
	
	private static List<Model> SERVERS=new ArrayList<Model>();
	

	/**
	 * 每30秒同步一次微服务列表
	 */
	@Scheduled(cron = "0/30 * * * * ?")
	private void load() {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		SERVERS=dao.select(Model.create());
	}
	
	/**
	 * 每10秒检测一次微服务状态
	 */
	@Scheduled(cron = "0/1 * * * * ?")
	private void detect() {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		for (Model server : SERVERS) {
			String ip=server.getString("ip");
			int timeOut = 2000;
	        try {
				boolean status = InetAddress.getByName(ip).isReachable(timeOut);
				if(status) {
					dao.update(Model.create().add("ip", ip).add("serverState", 1).add("checkTime",new Date()));
				}else {
					dao.update(Model.create().add("ip", ip).add("serverState", 0).add("checkTime",new Date()));
				}
			} catch (IOException e) {
				dao.update(Model.create().add("ip", ip).add("serverState", 0).add("checkTime",new Date()));
			}
		}
	}
	
	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		load();
	}
	
}
